import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-06-16
 * Time: 22:05
 */
public class TcpEchoServer {

    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");

        //这种情况一般不会使用 fixedThreadPool 意味着同时处理的客户端连接数目就固定了 企业级会有上千万甚至亿的客户端来访问
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true) {
            //tcp来说，需要先处理客户端发来的请求
            //通过写clientSocket 和客户端进行通信
            //如果没有客户端发来连接，则会一直阻塞在accept()方法上
            Socket clientSocket = serverSocket.accept();

           /* //多线程来处理多个客户端的请求
            Thread thread = new Thread(() -> {
                procrssConnection(clientSocket);
            });
            thread.start();*/

            //将任务提交给线程池
            executorService.submit(() -> {
                procrssConnection(clientSocket);
            });
        }
    }

    private void procrssConnection(Socket clientSocket) {
        System.out.printf("[%s:%d] 客户端上线！\n", clientSocket.getInetAddress(), clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            //针对InputStream套了个Scanner，可以方便的读取请求
            //作用就是从输入流中读取数据，并按行分割
            Scanner scanner = new Scanner(inputStream);
            //针对OutputStream套了个PrintWriter，可以方便的发送响应
            //作用就是把数据写到输出流中，并刷新缓冲区
            PrintWriter printWriter = new PrintWriter(outputStream);
            //分成三步骤
            while (true) {
                //1.读取请求并解析，可以直接read，也可以借助scanner来辅助完成
                if (!scanner.hasNext()) {
                    //连接断开
                    break;
                }

                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.发送响应到客户端
                //outputStream.write(response.getBytes());
                printWriter.println(response);
                printWriter.flush();

                //打印日志
                System.out.printf("[%s:%d] req：%s, resp: %s\n", clientSocket.getInetAddress(), clientSocket.getPort(), request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭客户端连接
                //防止多个客户端占满服务器资源
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }

    
}
